package com.zhang.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.entity.User;
import com.zhang.exception.BusinessException;
import com.zhang.responce.Result;
import com.zhang.responce.ResultCode;
import com.zhang.service.UserService;
import com.zhang.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Zhang
 * @since 2022-03-02
 */
@RestController
@RequestMapping("/user")
@Api(value = "系统用户模块", tags = "系统用户接口")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    @ApiOperation(value = "获取所有的用户", notes = "查询所有用户信息")
    public Result lsit() {
        List<User> list = userService.list();
        return Result.ok().data("users", list);
    }


    @PostMapping("/findUserPage")
    @ApiOperation(value = "分页查询的用户", notes = "分页条件查询用户信息")
    public Result findUserPage(@RequestParam(value = "current", required = true, defaultValue = "1") Integer current,
                               @RequestParam(value = "size", required = true, defaultValue = "5") Integer size,
                               @RequestBody(required = false) UserVO userVO) {
        Page<UserVO> page = new Page<>(current, size);
        page = userService.findUserPage(page, userVO);
        return Result.ok().data("userPage", page);
    }


    @PostMapping("/save")
    @ApiOperation(value = "用户列表", notes = "查询所有用户信息")
    public Result save(@RequestBody User user) {
        //判断参数是否为空
        if (user == null) {
            throw new BusinessException(ResultCode.PARAM_IS_BLANK.getCode()
                    , ResultCode.PARAM_IS_BLANK.getMessage());
        }
        //判断用户名是否存在
        List<User> list = userService.list(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (list != null) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode()
                    , ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        //判断添加是否成功
        boolean save = userService.save(user);
        if (!save) {
            return Result.error().code(ResultCode.COMMON_FAIL.getCode()).message(ResultCode.COMMON_FAIL.getMessage());
        }
        return Result.ok();
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除用户信息", notes = "")
    public Result delete(@PathVariable(value = "id") Long id) {
        boolean remove = userService.removeById(id);
        //判断删除是否成功
        if (!remove) {
            return Result.error().code(ResultCode.COMMON_FAIL.getCode()).message(ResultCode.COMMON_FAIL.getMessage());
        }
        return Result.ok();
    }

    @PutMapping("/modify")
    @ApiOperation(value = "修改用户信息", notes = "")
    public Result modify(@RequestBody User user) {
        boolean modify = userService.updateById(user);
        //判断修改是否成功
        if (!modify) {
            return Result.error().code(ResultCode.COMMON_FAIL.getCode()).message(ResultCode.COMMON_FAIL.getMessage());
        }
        return Result.ok();
    }

    @PatchMapping("/modifyStatus/{id}")
    @ApiOperation(value = "修改用户状态", notes = "有效状态改为锁定，反之改为有效")
    public Result modifystatus(@PathVariable(value = "id") Long id) {
        boolean modify = userService.modifyStatus(id);
        //判断修改是否成功
        if (!modify) {
            return Result.error().code(ResultCode.COMMON_FAIL.getCode()).message(ResultCode.COMMON_FAIL.getMessage());
        }
        return Result.ok();
    }

    @PostMapping("/excel")
    @ApiOperation(value = "导出Excel", tags = "导出Excel")
    public void excel(HttpServletResponse response,
                      @RequestBody(required = false) UserVO userVO) throws IOException {
        int count = userService.getBaseMapper().selectCount(null).intValue();
        Page<UserVO> page = new Page<>(1, count);
        page = userService.findUserPage(page, userVO);
        List<Long> ids = new ArrayList<>();
        for (UserVO record : page.getRecords()) {
            ids.add(record.getId());
        }
        List<User> users = userService.listByIds(ids);
        userService.exportUserExcel(response, users);
    }

    @PostMapping("/login")
    @ApiOperation(value = "登录方法",tags = "使用jwt实现登录")
    public Result login(@RequestParam(value = "username")String username,
                        @RequestParam(value = "password")String password,
                        HttpServletRequest request){
        //进行验证码或者短信校验

        String token = userService.login(username, password);

        //日志

        return Result.ok().data("token",token);
    }
}

